
import pynput
import time
import threading

class Actioner(object):
    def __init__(self):
        self.interrupted = False
        self.ctr_m = pynput.mouse.Controller()
        self.ctr_k = pynput.keyboard.Controller()
        self.listener2 = pynput.keyboard.Listener(
            on_release = self.on_release
        )
        self.listener2.start()


    def on_release(self, key):
        if(key == pynput.keyboard.Key.esc):
            # Stop listener
            self.listener2.stop()
            self.interrupted = True
            print('Stop listener')
            return False


    def start(self):

        with open('./record.txt', 'r') as f:
            lines = f.readlines()

            event = dict(eval(lines[0]))
            last_time = event['time']
            for line in lines:
                if self.interrupted:
                    break
                event = dict(eval(line))
                dif = event['time'] - last_time
                last_time = event['time']
                
                time.sleep(dif)

                _type = event['type']
                name = event['name']
                value = event['value']

                if _type == 'mouse':
                    if name == 'move':
                        #ctr_m.move(value[0], value[0])
                        self.ctr_m.position = tuple(value)
                        pass
                    elif  name == 'press':
                        if value == 'left':
                            self.ctr_m.press(pynput.mouse.Button.left)
                        elif value == 'right':
                            self.ctr_m.press(pynput.mouse.Button.right)
                        pass
                    elif  name == 'release':
                        if value == 'left':
                            self.ctr_m.release(pynput.mouse.Button.left)
                        elif value == 'right':
                            self.ctr_m.release(pynput.mouse.Button.right)
                        pass
                    elif  name == 'scroll':
                        self.ctr_m.scroll(value[0], value[1])
                        pass
                    pass
                elif _type == 'keyboard':
                    if name == 'press':
                        self.ctr_k.press(pynput.keyboard.KeyCode.from_vk(value[1]))
                        pass
                    elif  name == 'release':
                        self.ctr_k.release(pynput.keyboard.KeyCode.from_vk(value[1]))
                        pass
                    pass
        
        
if __name__ == "__main__":
    print("开始执行脚本")
    p = Actioner()
    p.start()
